/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Define class TCPSocket.
//
// TCPSocket is a wrapper of socket and it only supports TCP connection.
//

#ifndef __TCP__SOCKET__H
#define __TCP__SOCKET__H

#include <sys/socket.h>
#include <string>

#include "noncopyable.h"
#include "common.h"

namespace amz {

class TCPSocket : public noncopyable {
 public:
  explicit TCPSocket(int socket = 0);
  virtual ~TCPSocket();

  inline int GetSocket() const { return this->socket_; }

  // Create a socket.
  bool CreateSocket();

  // Connect to a server using server address - "ip" and server port - "port".
  bool Connect(const char *ip, uint16 port);

  // Bind IP and port.
  bool Bind(const char *ip, uint16 port);

  // Listen the socket.
  bool Listen(int max_connection);

  // Wait for a new connection, and save it's informations to these arguments.
  bool Accept(TCPSocket *tcp_socket, std::string *ip, uint16 *port);

  // Shutdown the socket according to the argument - shut_flag.
  bool Shutdown(int shut_flag);

  // Close the socket.
  bool Close();

  // Check link available.
  inline bool CheckAvailable() const { return this->link_available_; }
  // Set link available/unavailable.
  inline void SetAvailable() { this->link_available_ = true; }
  inline void SetUnavailable() { this->link_available_ = false;}

  // Send/Receive message.
  // return number of bytes if read/receive success.
  // < 0: error.
  virtual int Send(const char *message, int size);
  virtual int Receive(char *message, int size);

  // Nonblock pattern.
  bool SetNonblock();

 protected:
  int socket_;
  bool link_available_;
};

}  // namespace amz

#endif  // __TCP__SOCKET__H

